﻿using System;
using System.Collections.Specialized;
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

namespace University.Workshop.DataAccess
{
    public static class DataAccessBackUp
    {
        public static bool BackUpExist(string dir)
        {
            return File.Exists(dir + ".bak");
        }

        public static void DeleteBackUp(string dir)
        {
            File.Delete(dir);
        }

        public static void CreateBackUp(string dir, string file)
        {
            string DbName = WFPEntities.Instance.Database.Connection.Database;
            ServerConnection con = new ServerConnection(@".\SQLEXPRESS");
            Server server = new Server(con);
            Backup source = new Backup();
            source.Action = BackupActionType.Database;
            source.Database = DbName;
            BackupDeviceItem destination = new BackupDeviceItem(Path.Combine(dir,file+".bak"), DeviceType.File);
            source.Devices.Add(destination);
            source.SqlBackup(server);
            con.Disconnect();

//            bool IsExists = System.IO.Directory.Exists(dir);

//            if (!IsExists)
//                System.IO.Directory.CreateDirectory(dir);

//            WFPEntities.Instance.Database.ExecuteSqlCommand(@"
//use [master] 
//backup database [WFPDB] to disk='" +
//                                                            @Path.Combine(dir, file) + ".bak'");

            //Backup sqlBackup = new Backup
            //                       {
            //                           Action = BackupActionType.Database,
            //                           BackupSetDescription = "ArchiveDataBase:" + DateTime.Now.ToShortDateString(),
            //                           BackupSetName = file,
            //                           Initialize = true,
            //                           Checksum = true,
            //                           ContinueAfterError = false,
            //                           Database = "WFPDB",
            //                           Incremental = false,
            //                           LogTruncation = BackupTruncateLogType.Truncate,
            //                           FormatMedia = false
            //                       };

            //sqlBackup.Devices.Add(new BackupDeviceItem(dir, DeviceType.File));
            //string m = WFPEntities.Instance.Database.Connection.DataSource;
            //sqlBackup.SqlBackup(new Server(new ServerConnection(WFPEntities.Instance.Database.Connection.DataSource)));




            //Backup sqlBackup = new Backup();

            //sqlBackup.Action = BackupActionType.Database;
            //sqlBackup.BackupSetDescription = "ArchiveDataBase:" +
            //                                 DateTime.Now.ToShortDateString();
            //sqlBackup.BackupSetName = "Archive";

            //sqlBackup.Database = "WFPDB";

            //BackupDeviceItem deviceItem = new BackupDeviceItem(dir, DeviceType.File);
            //ServerConnection connection = new ServerConnection(WFPEntities.Instance.Database.Connection.ConnectionString);
            //Server sqlServer = new Server(connection);
            //Database db = sqlServer.Databases["WFPDB"];

            //sqlBackup.Initialize = true;
            //sqlBackup.Checksum = true;
            //sqlBackup.ContinueAfterError = true;

            //sqlBackup.Devices.Add(deviceItem);
            //sqlBackup.Incremental = false;

            //sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
            //sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

            //sqlBackup.FormatMedia = false;

            //sqlBackup.SqlBackup(sqlServer);
        }

        public static bool ExistDataBase()
        {
            WFPEntities.Instance.DiscardChanges();
            return WFPEntities.Instance.Database.Exists();
        }

        public static void MakeBackUp(string p)
        {

            //string DbName = WFPEntities.Instance.Database.Connection.Database;
            //Restore sqlRestore = new Restore();

            //BackupDeviceItem deviceItem = new BackupDeviceItem(p, DeviceType.File);
            //sqlRestore.Devices.Add(deviceItem);
            //sqlRestore.Database = DbName;
            //SqlConnection n= new SqlConnection(WFPEntities.Instance.Database.Connection.ConnectionString);
            //ServerConnection connection = new ServerConnection(n);
            //Server sqlServer = new Server(connection);

            //Database db = sqlServer.Databases[DbName];
            //sqlRestore.Action = RestoreActionType.Database;
            //db = sqlServer.Databases[DbName];
            //sqlRestore.ReplaceDatabase = true;
            //sqlRestore.SqlRestore(sqlServer);   
            //db.SetOnline();
            //sqlServer.Refresh();


            //string DbName = WFPEntities.Instance.Database.Connection.Database;
            //ServerConnection conn = new ServerConnection(@".\SQLEXPRESS", "Javier", "");

            //Server localServer = new Server(conn); //local using windows athuentication

            //Restore backupMgr = new Restore();
            //backupMgr.Devices.AddDevice(@p, DeviceType.File);
            //backupMgr.Database = DbName;
            //backupMgr.Action = RestoreActionType.Database;
            //backupMgr.ReplaceDatabase = true;
            //backupMgr.NoRecovery = false;
            
            //backupMgr.SqlRestore(localServer);



            //WFPEntities.Instance.DiscardChanges();
            //string DbName = WFPEntities.Instance.Database.Connection.Database;
            ////WFPEntities.Instance.Database.Delete();
            //var con = new ServerConnection(@".\SQLEXPRESS");
            //var server = new Server(con);
            //var destination = new Restore { Action = RestoreActionType.Database, Database = DbName, ReplaceDatabase = true };
            //destination.SqlRestore(server);
            //destination.Devices.Add(new BackupDeviceItem(p, DeviceType.File));
            //WFPEntities.Instance.DiscardChanges();


//            WFPEntities.Instance.DiscardChanges();
//            string DbName = WFPEntities.Instance.Database.Connection.Database;
//            WFPEntities.Instance.Database.Delete();

//            var myConnection = new SqlConnection(WFPEntities.Instance.Database.Connection.ConnectionString);
//            myConnection.Open();
//            string SQL = string.Format(@"
//use [{1}]
//RESTORE DATABASE WFPDB
//from disk = '{0}'
//", @p, DbName);
//            var myCommand = new SqlCommand(SQL, myConnection);


//            myCommand.ExecuteNonQuery();


//            myConnection.Close();





            String databaseName = WFPEntities.Instance.Database.Connection.Database;
            String filePath = p;
            String serverName = @WFPEntities.Instance.Database.Connection.DataSource;
    Restore sqlRestore = new Restore();

    BackupDeviceItem deviceItem = new BackupDeviceItem
			(filePath, DeviceType.File);
    sqlRestore.Devices.Add(deviceItem);
    sqlRestore.Database = databaseName;

        SqlConnection sqlCon = new SqlConnection
	(@"Data Source="+serverName+@"; Integrated Security=True;"); 
        ServerConnection connection = new ServerConnection(sqlCon);   
    Server sqlServer = new Server(connection);

    Database db = sqlServer.Databases[databaseName];
    sqlRestore.Action = RestoreActionType.Database;
    db = sqlServer.Databases[databaseName];

    sqlRestore.ReplaceDatabase = true;
    sqlRestore.PercentCompleteNotification = 10;
            WFPEntities.Instance.Database.Delete();
        sqlRestore.SqlRestore(sqlServer);


    db = sqlServer.Databases[databaseName];

    db.SetOnline();

    sqlServer.Refresh();
            WFPEntities.Instance.DiscardChanges();
        }
    }
}
